#include "QuFile.h"

QStringList QuFile::readLines(const QString& filePath, bool triming, bool ignoreEmptyLine)
{
    QFile f(filePath);
    if (!f.open(QFile::ExistingOnly | QFile::ReadOnly | QFile::Text))
        return QStringList();

    QStringList sl;
    while(f.bytesAvailable() > 0) {
        auto line = f.readLine();
        if(line.back() == '\n') line.removeLast();
        if (triming)
            line = line.trimmed();
        if (line.isEmpty() && ignoreEmptyLine) // 空行?
            continue;

        sl << QString::fromStdString(line.toStdString());
    }

    return sl;
}

bool QuFile::writeLines(const QString& filePath, const QStringList& lines, bool append)
{
    QFile f(filePath);
    if (!f.open(QFile::WriteOnly | QFile::Text | (append ? QFile::Append : QFile::Truncate)))
        return false;

    for(auto& i : lines) {
        if (!writeLine(f, i))
            return false;
    }

    return true;
}

bool QuFile::appendLine(const QString& filePath, const QString& line)
{
    QFile f(filePath);
    if (!f.open(QFile::WriteOnly | QFile::Append | QFile::Text))
        return false;

    return writeLine(f, line);
}

bool QuFile::writeLine(QFile& file, const QString& line)
{
    auto str = line.toStdString(); str += '\n';
    return file.write(str.data(), str.length()) == str.length();
}
